package cn.itcast.web.controller.cargo;


import cn.itcast.domain.cargo.IncasementProxy;
import cn.itcast.service.cargo.ShippingService;
import cn.itcast.vo.ContractProductVo;
import cn.itcast.web.controller.BaseController;
import cn.itcast.web.utils.DownloadUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.sql.DataSource;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/cargo/shipping")
public class ShippingController extends BaseController {

    @Reference
    private ShippingService shippingService;

    @Autowired
    private DataSource dataSource;

    @RequestMapping("/list")
    public String list(@RequestParam(defaultValue = "1") int pageNum, @RequestParam(defaultValue = "5")int pageSize){
        PageInfo<IncasementProxy> pageInfo=shippingService.findByPage(pageNum,pageSize);
        request.setAttribute("pageInfo",pageInfo);
        System.out.println("pageInfo为"+pageInfo);
        return "cargo/shipping/shipping-list";
    }

    @RequestMapping("/delete")
    @ResponseBody
    public Map<String,Object> delete(String shippindOrderId){
        Map<String,Object> resultMap = new HashMap<>();
        boolean flag=shippingService.delete(shippindOrderId);
        if(flag){
            resultMap.put("message","删除成功");
        }else{
            resultMap.put("message","删除失败，该委托单已开票");
        }
        resultMap.put("flag",flag);

        return resultMap;
    }

    @RequestMapping("/toAdd")
    public String toAdd(){
        return "cargo/shipping/shipping-add";
    }

    @RequestMapping("add")
    public String add(IncasementProxy incasementProxy){
        incasementProxy.setCreateBy(getLoginUser().getUserName());
        incasementProxy.setCreateDept(getLoginUser().getDeptName());
        incasementProxy.setCreateTime(new Date());
        shippingService.add(incasementProxy);
        return "redirect:/cargo/shipping/list.do";
    }


    /**
     * 导出Excel格式的出货表
     *   路径： http://localhost:8080/cargo/contract/printExcel.do
     *   参数：inputDate=2019-06
     *   返回：excel文件
     */
    @RequestMapping("/printExcel")
    public void printExcel(String inputDate) throws IOException {

        //1.创建工作簿
        Workbook wb = new XSSFWorkbook();


        //2.生成工作单
        Sheet sheet = wb.createSheet("委托单表");
        //设置合并列
        /**
         * 参数依次为： 开始行号，结束行号，开始列号，结束列号
         */
        sheet.addMergedRegion(new CellRangeAddress(0,0,1,8));
        //设置列宽， 参数为：列索引，列宽度值
        sheet.setColumnWidth(0,6*256);
        sheet.setColumnWidth(1,21*256);
        sheet.setColumnWidth(2,16*256);
        sheet.setColumnWidth(3,29*256);
        sheet.setColumnWidth(4,11*256);
        sheet.setColumnWidth(5,11*256);
        sheet.setColumnWidth(6,11*256);
        sheet.setColumnWidth(7,11*256);
        sheet.setColumnWidth(8,11*256);
        sheet.setColumnWidth(9,11*256);

        //3.创建表头行
        Row row = sheet.createRow(0);
        //3.4.设置行高度
        row.setHeightInPoints(36);

        //inputDate: 2019-10 或 2019-08
        //3.1 设置标题
        String title = "委托单表";
        //3.2 设置第二列的内容作为标题
        Cell cell = row.createCell(1);
        cell.setCellValue(title);
        //3.3 设置大标题样式
        cell.setCellStyle(bigTitle(wb));


        //4.创建内容行
        //4.1 创建标题
        row = sheet.createRow(1);

        String[] titles = {"运输方式","货主","提单抬头","正本通知人","信用证","装运港","转船港","卸货港","装期","效期","是否分批","是否转船","份数","扼要说明","运输要求","运费说明","复核人","状态","创建人","创建部门","创建日期"};
        for(int i=0;i<titles.length;i++){
            cell = row.createCell(i + 1);
            cell.setCellValue(titles[i]);
            //设置样式
            cell.setCellStyle(title(wb));
        }

        //4.2 内容
        //查询数据库获取内容
        int index = 2;
        List<IncasementProxy> list = shippingService.findAll(getLoginUser().getDeptName());

        if(list!=null){
            for(IncasementProxy incasementProxy:list){


                //创建行
                row = sheet.createRow(index++);


                //设置行高
                row.setHeightInPoints(24);

                //设置列内容


                //客户列
                cell = row.createCell(1);


                if(incasementProxy.getOrderType()!=null) {

                    //样式
                    cell.setCellStyle(text(wb));
                    //内容
                    cell.setCellValue(incasementProxy.getOrderType());
                }

                //订单列
                cell = row.createCell(2);
                if(incasementProxy.getShipper()!=null) {

                    //样式
                    cell.setCellStyle(text(wb));
                    //内容
                    cell.setCellValue(incasementProxy.getShipper());
                }
                //货号列
                cell = row.createCell(3);
                if(incasementProxy.getConsignee()!=null) {

                    //样式
                    cell.setCellStyle(text(wb));
                    //内容
                    cell.setCellValue(incasementProxy.getConsignee());
                }

                //数量列
                cell = row.createCell(4);
                if(incasementProxy.getNotifyParty()!=null) {

                    //样式
                    cell.setCellStyle(text(wb));
                    //内容
                    cell.setCellValue(incasementProxy.getNotifyParty());
                }

                //工厂列
                cell = row.createCell(5);
                if(incasementProxy.getLcNo()!=null) {

                    //样式
                    cell.setCellStyle(text(wb));
                    //内容
                    cell.setCellValue(incasementProxy.getLcNo());
                }

                //交期列
                cell = row.createCell(6);
                if(incasementProxy.getPortOfLoading()!=null) {

                    //样式
                    cell.setCellStyle(text(wb));
                    //内容
                    cell.setCellValue(incasementProxy.getPortOfLoading());
                }

                //船期列
                cell = row.createCell(7);
                if(incasementProxy.getPortOfTrans()!=null) {

                    //样式
                    cell.setCellStyle(text(wb));
                    //内容
                    cell.setCellValue(incasementProxy.getPortOfTrans());
                }

                //贸易条款列
                cell = row.createCell(8);
                if(incasementProxy.getPortOfDischar()!=null) {
                    //样式
                    cell.setCellStyle(text(wb));
                    //内容
                    cell.setCellValue(incasementProxy.getPortOfDischar());
                }

                cell = row.createCell(9);
                if(incasementProxy.getLoadingDate()!=null) {
                    //样式
                    cell.setCellStyle(text(wb));
                    //内容
                    cell.setCellValue(incasementProxy.getLoadingDate());
                }

                cell = row.createCell(10);
                if(incasementProxy.getLimitDate()!=null) {
                    //样式
                    cell.setCellStyle(text(wb));
                    //内容
                    cell.setCellValue(incasementProxy.getLimitDate());
                }

                cell = row.createCell(11);
                if(incasementProxy.getIsBatch()!=null) {
                    //样式
                    cell.setCellStyle(text(wb));
                    //内容
                    cell.setCellValue(incasementProxy.getIsBatch());
                }

                cell = row.createCell(12);
                if(incasementProxy.getIsTrans()!=null) {
                    //样式
                    cell.setCellStyle(text(wb));
                    //内容
                    cell.setCellValue(incasementProxy.getIsTrans());
                }


                cell = row.createCell(13);
                if(incasementProxy.getCopyNum()!=null) {
                    //样式
                    cell.setCellStyle(text(wb));
                    //内容
                    cell.setCellValue(incasementProxy.getCopyNum());
                }

                cell = row.createCell(14);
                if(incasementProxy.getRemark()!=null) {
                    //样式
                    cell.setCellStyle(text(wb));
                    //内容
                    cell.setCellValue(incasementProxy.getRemark());
                }


                cell = row.createCell(15);
                if(incasementProxy.getSpecialConditio()!=null) {
                    //样式
                    cell.setCellStyle(text(wb));
                    //内容
                    cell.setCellValue(incasementProxy.getSpecialConditio());
                }

                cell = row.createCell(16);
                if(incasementProxy.getFreight()!=null) {
                    //样式
                    cell.setCellStyle(text(wb));
                    //内容
                    cell.setCellValue(incasementProxy.getFreight());
                }

                cell = row.createCell(17);
                if(incasementProxy.getCheckBy()!=null) {
                    //样式
                    cell.setCellStyle(text(wb));
                    //内容
                    cell.setCellValue(incasementProxy.getCheckBy());
                }
                cell = row.createCell(18);
                    //样式
                cell.setCellStyle(text(wb));
                    //内容
                cell.setCellValue(incasementProxy.getState());


                cell = row.createCell(19);
                if(incasementProxy.getCreateBy()!=null) {
                    //样式
                    cell.setCellStyle(text(wb));
                    //内容
                    cell.setCellValue(incasementProxy.getCreateBy());
                }

                cell = row.createCell(20);
                if(incasementProxy.getCreateDept()!=null) {
                    //样式
                    cell.setCellStyle(text(wb));
                    //内容
                    cell.setCellValue(incasementProxy.getCreateDept());
                }

                cell = row.createCell(21);
                if(incasementProxy.getCreateTime()!=null) {
                    //样式
                    cell.setCellStyle(text(wb));
                    //内容
                    cell.setCellValue(incasementProxy.getCreateTime());
                }


            }

        }

        //3.把工作簿写出到浏览器响应（给用户下载Excel)

      /*  //3.2. 设置写出的文件格式： excel格式
        response.setContentType("application/octet-stream;charset=utf-8");
        //3.2 提示浏览器一个下载的文件名称: Content-Disposition
        response.addHeader("Content-Disposition","attachment;filename=product.xlsx");

        OutputStream outputStream = response.getOutputStream();

        //3.3 把工作簿写出到响应中
        wb.write(outputStream);
        outputStream.flush();*/

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        wb.write(outputStream);
        new DownloadUtil().download(outputStream,response,"委托单表.xlsx");
    }


    //大标题的样式
    public CellStyle bigTitle(Workbook wb){
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("宋体");
        font.setFontHeightInPoints((short)16);
        font.setBold(true);//字体加粗
        style.setFont(font);
        style.setAlignment(HorizontalAlignment.CENTER);				//横向居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);		//纵向居中
        return style;
    }

    //小标题的样式
    public CellStyle title(Workbook wb){
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("黑体");
        font.setFontHeightInPoints((short)12);
        style.setFont(font);
        style.setAlignment(HorizontalAlignment.CENTER);				//横向居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);		//纵向居中
        style.setBorderTop(BorderStyle.THIN);						//上细线
        style.setBorderBottom(BorderStyle.THIN);					//下细线
        style.setBorderLeft(BorderStyle.THIN);						//左细线
        style.setBorderRight(BorderStyle.THIN);						//右细线
        return style;
    }

    //文字样式
    public CellStyle text(Workbook wb){
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("Times New Roman");
        font.setFontHeightInPoints((short)10);

        style.setFont(font);

        style.setAlignment(HorizontalAlignment.LEFT);				//横向居左
        style.setVerticalAlignment(VerticalAlignment.CENTER);		//纵向居中
        style.setBorderTop(BorderStyle.THIN);						//上细线
        style.setBorderBottom(BorderStyle.THIN);					//下细线
        style.setBorderLeft(BorderStyle.THIN);						//左细线
        style.setBorderRight(BorderStyle.THIN);						//右细线

        return style;
    }

    /*
  url:/cargo/export/exportPdf.do?id=5a3680c7-c3eb-4e22-a8f1-f733fb4f1a9e
  作用： 下载电子报运单pdf版本
  参数： 报运单的id
  返回值： 下载
   */
    @RequestMapping("/printPDF")
    @ResponseBody
    public  void exportPdf(String id) throws Exception {
        //通知浏览器以文件下载的方式处理内容
        String  fileName = "委托单.pdf";
        fileName =  URLEncoder.encode(fileName,"utf-8");

        //1. 找到模板的输入流
        InputStream inputStream = session.getServletContext().getResourceAsStream("/jasper/incasementProxy.jasper");



        JasperPrint jasperPrint = JasperFillManager.fillReport(inputStream, new HashMap<>(), dataSource.getConnection());
        response.setContentType("application/pdf;charset=utf-8");
        response.setHeader("content-disposition","attachment;filename="+fileName);
        //3. 把pdf输出
        JasperExportManager.exportReportToPdfStream(jasperPrint,response.getOutputStream());
    }

}
